package utils

import (
	"context"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"strings"
	"time"
)

var jwtKey = []byte("your_secret_key") // 请替换为强密钥

type Claims struct {
	UserID   int    `json:"user_id"`
	Realname string `json:"realname"` // 假设你有这个字段，用于存储用户的真实姓名或其他相关的用户信息
	jwt.RegisteredClaims
}

func GenerateToken(userID int, realname string) (string, error) {
	expirationTime := time.Now().Add(24 * time.Hour)

	claims := &Claims{
		UserID:   userID,
		Realname: realname,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
}

func ValidateToken(tokenStr string) (*Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, jwt.ErrSignatureInvalid
	}

	return claims, nil
}

func RefreshToken(tokenStr string) (string, error) {
	// 先验证原始token
	claims, err := ValidateToken(tokenStr)
	if err != nil {
		return "", err
	}

	// 更新过期时间
	newExpirationTime := time.Now().Add(24 * time.Hour)
	claims.ExpiresAt = jwt.NewNumericDate(newExpirationTime)

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
	// 生成新token
	
}

func JwtMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			CustomError(w, "未提供认证token", http.StatusUnauthorized)
			return
		}

		tokenString := strings.TrimPrefix(authHeader, "Bearer ")
		claims, err := ValidateToken(tokenString)
		if err != nil {
			CustomError(w, "无效token", http.StatusUnauthorized)
			return
		}

		// 创建新的请求上下文并添加用户信息
		ctx := context.WithValue(r.Context(), "user_id", claims.UserID)
		ctx = context.WithValue(ctx, "realname", claims.Realname)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
